'''
python 调用lua 函数
# https://tool.4xseo.com/article/202945.html

'''
import lupa
import json
import time


def table_conver_dict(tablev, dictv):
    '''
    {"error_code":0,
    "error_message":None,
    "result":{}
    }
    将lua的 table 表结构转为python dict字典
    table中不含 nil 同意使用'None' 
    遇到列表特殊处理
    '''
    templist = []
    valueone = None
    for key, value in tablev.items():
        # print(f'{key},{value},{str(type(value))}')
        if type(key) in [str]:
            if type(value) in [str] and value == 'None':
                dictv[key] = None
            if type(value) in [str, int]:
                dictv[key] = value
            elif type(value) in [dict] or lupa.lua_type(value) in ['table']:
                dictv[key] = {}
                a = table_conver_dict(value, dictv[key])
                if a:
                    dictv[key] = a
        elif type(key) in [int] and key == 1:
            templist = []
            if type(value) in [str] and value == 'None':
                valueone = None
            elif type(value) in [str, int]:
                valueone = value
            elif type(value) in [dict] or lupa.lua_type(value) in ['table']:
                valueone = {}
                a = table_conver_dict(value, valueone)
                if a:
                    valueone = a
            templist.append(valueone)
        elif type(key) in [int]:
            if type(value) in [str] and value == 'None':
                valueone = None
            elif type(value) in [str, int]:
                valueone = value
            elif type(value) in [dict] or lupa.lua_type(value) in ['table']:
                valueone = {}
                a = table_conver_dict(value, valueone)
                if a:
                    valueone = a
            templist.append(valueone)
    if templist:
        return templist
    else:
        return False


if __name__ == '__main__':
    time_extractor = {
        "begin": {
            "date": "2023-02-02",
            "period": "下午",
            "time": "15:30:00",
            "week": "星期四"
        },
        "type": "time_point"
    }

    biz_home_kg = {
        "domain_intent": [
            {
                "coordinate_position": None,
                "entity": "",
                "space": "卧室",
                "space_id": 0,
                "space_type": "",
                "intent": "预约区域清洁_清洁",
                "exist": True,
                "area_id": "1003",
                "furniture_id": "",
                "direction": ""
            }
        ],
        "command_param_origin": [
            "1003"
        ],
        "command_param": "1003",
        "command_param_value": "location",
        "clean_mode": "clean",
        "answer_message": "卧室",
        "map_id": "",
        "exist": True,
        "error_message": "",
        "coordinate_position": []
    }
    othernlu = [
        {
            "entity": [
                {
                    "ACTION": {
                        "attribute": [],
                        "start": 7,
                        "value": "打扫"
                    },
                    "DIRECTION": {},
                    "DISTANCE": {},
                    "FURNITURE": {},
                    "SPACE": {
                        "attribute": [],
                        "start": 9,
                        "value": "卧室"
                    },
                    "TIMES": {}
                }
            ],
            "intent": "预约区域清洁_清洁",
            "score": 0.994383335,
            "time": "明天下午3点半"
        }
    ]
    # 实例化一个lua解释器
    lua = lupa.LuaRuntime()

# [
#         {
#             "time": [
#                 {
#                     "slot_type": "TIME",
#                     "text": "30号早上8点",
#                     "value": {
#                         "begin": {
#                             "date": "2021-11-30",
#                             "time": "08:00:00",
#                         },
#                         "type": "time_point"
#                     }
#                 }
#             ],
#             "space":[
#                 {
#                     "slot_type":"LOCATI0N",
#                     "text":"1000",
#                     "value":"location"
#                 }
#             ],
#             "domain": "smart_home.clean_robot_time",
#             "intent": "start_clean",
#             "slots": null
#         }
#     ]

    valuechange = '''
        function(othernlu,biz_home_kg,time_extractor)
            othernlu_t = { }
            for index, item in python.enumerate(othernlu) do
                othernlu_t[index+1] = item
            end
            print(othernlu_t[1],type(othernlu_t[1]))
            local t = { }
            local time = { }
            local space={ }
            local domain = "smart_home.clean_robot_time"
            local intent = "start_clean"
            local slots = "None"
            time[1] = {}
            time[1]["slot_type"] = "TIME"
            time[1]["text"] = othernlu_t[1]["time"]
            time[1]["value"] = time_extractor
            space[1] ={}
            space[1]["slot_type"] = "LOCATI0N"
            space[1]["text"] = biz_home_kg["command_param"]
            space[1]["value"] = biz_home_kg['command_param_value']
            t[1] = {}
            t[1]['time'] =time 
            t[1]['space'] =space 
            t[1]['domain'] =domain 
            t[1]['intent'] =intent 
            t[1]['slots'] =slots 


            return t
        end
        '''
    lua_func = lua.eval(valuechange)
    # starttime = time.time()
    r = lua_func(othernlu, lupa.as_itemgetter(biz_home_kg), lupa.as_itemgetter(time_extractor)
                 )
    # print(time.time()-starttime)
    print(r, type(r))  # 6
    result = {}
    starttime = time.time()
    a = table_conver_dict(r, result)
    if a:
        result = a
    print(time.time()-starttime)
    print(result, type(result))
    print(json.dumps(result))
